<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Account/classes/PhpFox_ComponentAdminBrowse.class.php, $Author:  $ */

/** Component for showing and manipulating members in admin area
 *
 * @version $Id: PhpFox_ComponentAdminBrowse.class.php 403 2008-03-12 11:41:48Z phpfoxsv $
 * @package module.account
 */
class PhpFox_Mod_Account_ComponentAdminBrowse extends BaseComponent
{
    function process()
    {
        $oAccountItem = $this->_oModule->getItem('Account');
        /* @var $oAccountItem PhpFox_Mod_Account_ItemAccount */
        $oAccountService = $this->_oModule->getService('Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = $this->_oModule->getService('Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oReq = &App::getRequest();
        $oUrl = &App::getUrl();
        $oTpl = $this->_oModule->getTemplate();
        App::loadClass('Pager');
        App::loadClass('Filter');

        if (!$oSecurityService->hasStaffPerm('MENU_most_active'))
        {
            App::gotoUrl('admin.main');
        }
        $sCurrentUser = $oSecurityService->getCurrentUser();
        $iMembership = $oSecurityService->getMembership($sCurrentUser);
        $bIsAdmin = $oSecurityService->isAdmin();
        $bCanDelete = true;
        if (!$bIsAdmin)
        {
            $bCanDelete = $oSecurityService->hasStaffPerm('ACTION_delete_member');
        }
        
        if (($sBonusUser = $oReq->get('bonus_user')) && ($iBonus = $oReq->get('bonus')) && is_numeric($iBonus)) 
        {
        	$this->oDatabase->query("UPDATE " . App::getT('user_info') . " SET bonus = bonus+" . $iBonus . ", total = total+" . $iBonus . " WHERE user = '" . $this->oDatabase->escape($sBonusUser) . "'");
        	App::forward(App::makeUrl('admin.main.members'), App::format('Mod_Account.bonus_points_added'), 'message', App::getPageName(), 'browse');
        }        
        
        if (($sPointsUser = $oReq->get('points_user')) && (isset($_POST['points'])))
        {
       		$this->oDatabase->update(App::getT('user_info'), array('total' => $_POST['points']), "user = '" . $this->oDatabase->escape($sPointsUser) . "'");
       		App::forward(App::makeUrl('admin.main.members'), App::format('Mod_Account.points_updated'), 'message', App::getPageName(), 'browse');
        }        

        if ( $oReq->get('verify') && $id = $oReq->get('id') )
        {
        	$this->oDatabase->query("UPDATE ". App::getT('user') ." SET verify = '' ".
        		" WHERE id = '". $id ."' ");
			App::forward(App::makeUrl('admin.main.members'), App::format('admin.verify.confirm'), 'message', App::getPageName(), 'browse');
        }

        if ($sUserName = $oReq->get('changepic'))
        {
            $oAccountService->deleteUserPicture($sUserName);
            $oUrl->clearParams('changepic');
            App::forward($oUrl->getUrl(), App::format('Mod_Account.user_picture_updated'), 'message', App::getPageName(), 'browse');
        }
        if (($iUserId = $oReq->get('delete')) && $bCanDelete)
        {
            $oAccountItem->load($iUserId);
            if ($oAccountItem->aData['type'] != 0)
            {
                $oAccountService->delete($iUserId);
            }
            $oUrl->clearParams('delete');
            App::forward($oUrl->getUrl(), App::format('Mod_Account.user_deleted'), 'message', App::getPageName(), 'browse');
        }
        if ($iUserId = $oReq->get('login'))
        {
            $oAccountItem->load($iUserId);
            if ($oAccountItem->aData['type'] > 0)
            {
                if ( $oSecurityService->loginByAdmin($iUserId) )
                {
                	$bLoggedId = true;
                }
            }
            // App::gotoUrl('public.account');
        }
        if ($oReq->getAction() == 'membership')
        {
            $iUserId = $oReq->getInt('user');
            if ($iUserId)
            {
            	$iMembership = $oReq->getInt('membership');
                $oAccountService->setMembership($iUserId, $iMembership, 1, 1);
            }
            $oUrl->clearParams('membership');
            $oUrl->clearParams('user');
            App::forward($oUrl->getUrl());
        }
        if ($oReq->getAction() == 'ban')
        {
            $iUserId = $oReq->getInt('user');
            phpFoXPlugins::call_phpfox_function('ban_user',$iUserId);
            if ($iUserId)
            {
                $oAccountItem->load($iUserId);
                $oAccountItem->aData['is_banned'] = ($oReq->get('ban', 1)) ? 1 : 0;
                $oAccountItem->update(array('is_banned'));
            }
            $oUrl->clearParams('user');
            App::forward($oUrl->getUrl());
        }

		$aMemberships = array();
		$aModuleType = $this->oDatabase->getRows("SELECT membership_id, title FROM ". App::getT('membership') ." ORDER BY membership_id DESC");
        foreach ($aModuleType as $aMembership)
        {
            if (isset($aMembership['membership_id']) && ($aMembership['membership_id'] != 2))
            {
                $aMemberships[$aMembership['membership_id']] = $aMembership['title'];
            }
        }
        
        if (App::getUser('type') == '1')
        {
        	unset($aMemberships[0]);
        }

        $iPage = $oReq->getInt('page', 1);
        $iPageSize = App::getParam('admin.pagesize');
        $aStatus = array();
        $aStatus[''] = App::format('core.all');
        $aStatus['active'] = App::format('core.active');
        $aStatus['notu'] = App::format('core.banned');
        $aStatus['notv'] = App::format('Mod_Account.not_verfied');

        $aCacheGroups = $aMemberships;
        $aCacheGroups[''] = App::format('core.all');

        $aFields = array
        (
        	'user'      => 'like',
        	'email' => 'like',
        	'login_ip' => 'like',
            'status' => array
            (
                'value'  => '=',
                'select' => $aStatus
            ),
            'type' => array
            (
            	'value' => '=',
            	'select' => $aCacheGroups
            )
        );
        $oFilter = &new Filter('mbrowse', $aFields);

        $aCond = array();
        foreach ($oFilter->aConditions as $sKey => $sValue)
        {
        	if ( $sKey == 'status' )
        	{
        		$sType = $oFilter->aData['status'];
        		switch($sType)
        		{
        			case 'active':
        			$sValue = preg_replace('#{\#(.*)}#i', 'verify', $sValue);
                	$aCond[] = str_replace('active', '', $sValue);
        			break;
        			case 'notu':
        			$sValue = preg_replace('#{\#(.*)}#i', 'is_banned', $sValue);
                	$aCond[] = str_replace('notu', '1', $sValue);
        			break;
        			case 'notv':
        			$sValue = preg_replace('#{\#(.*)}#i', 'verify', $sValue);
                	$aCond[] = str_replace('notv', '1', $sValue);
        			break;
        		}
        	}
        	elseif ($sKey == 'login_ip')
        	{
        		$sValue = preg_replace('#{\#(.*)} LIKE#i', '', $sValue);
        		$sValue = $this->oDatabase->escape(trim(trim($sValue), '"'));
        		$aCond[] = " (login_ip LIKE '". $sValue ."' OR signup_ip LIKE '" . $sValue . "')";
        	}
        	elseif ( $sKey == 'type' )
        	{
        		$iType = $oReq->get('type');
        		if ( $iType == '0' || $iType != '' )
        		{
        			$oFilter->aHtml['type']['value'] = $iType;
					$aCond[] = " type = '". $iType ."'";
				}
				else
				{
					$aCond[] = $sValue;
				}
        	}
        	else
        	{
        		$aCond[] = $sValue;
        	}
        }

        if ( $oReq->get('type') != '' || $oReq->get('type') == '0' )
        {
        	$aCond['type'] = " = '". $oReq->get('type') ."'";
        }

        list($aItems, $iCnt) = $oAccountItem->getList($aCond, $iPage, $iPageSize, 'id DESC');
        foreach ($aItems as $iKey => $aItem)
        {
            $oUserItem = $oAccountService->getById($aItem['id']);
            $aItems[$iKey]['used_space']      = $oAccountService->getUsedSpace($aItem['user'], false, $aItem['id']);
            $aItems[$iKey]['activity_points'] = $oAccountService->getUserPoints($oUserItem);
            $aItems[$iKey]['membership']      = $oSecurityService->getMembershipName($aItem['type']);
            $aItems[$iKey]['membership_icon'] = $oAccountService->getMembershipImageByType($aItem['type']);
            $aItems[$iKey]['can_change'] = (App::getUser('type') == '1' && $aItem['type'] == '0' ? false : true);
        }
        $oPager = &new Pager($iCnt, $iPage, $iPageSize);
        $iFrom = $oPager->getOffset($iPage, $iPageSize);
        $iTo = (($iFrom + $iPageSize) > $iCnt) ? $iCnt : ($iFrom + $iPageSize);

        
		$oTpl->assignSrc('aFilter', $oFilter->aHtml);
        $oTpl->assign(array(
        	// 'aFilter'      => $oFilter->aHtml,
        	'iFrom'        => ($iCnt) ? ($iFrom + 1) : 0,
        	'iTo'          => $iTo,
        	'aItems'       => $aItems,
            'iMembership'  => $iMembership,
        	'aMemberships' => $aMemberships,
        	'aPaging'      => ($iCnt) ? $oPager->getInfo($oUrl) : '',
        	'iCnt'         => $iCnt,
        	'sMImageUrl'   => App::getParam('membership.pic.url'),
        	'sUImageUrl'   => App::getParam('user.pic.url'),
            'bCanDelete'   => $bCanDelete,
            'bLoggedId' => (isset($bLoggedId) ? $bLoggedId : ''),
            'bShowPoints'      => !App::getSetting('profile_display_points'),
            'bCanLogin' => $oSecurityService->isStaffAllowed('admin.extra.snoop')
        ));
        return $oTpl->fetch('AdminBrowseList.html');
    }
}
?>